package cn.shyouchi.wuguanjia.android.ui.workshow;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Environment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.shyouchi.wuguanjia.android.Global;
import cn.shyouchi.wuguanjia.android.R;
import cn.shyouchi.wuguanjia.android.api.show.ShowApi;
import cn.shyouchi.wuguanjia.android.base.BaseActivity;
import cn.shyouchi.wuguanjia.android.event.DataChangeEvent;
import cn.shyouchi.wuguanjia.android.event.LikeChange;
import cn.shyouchi.wuguanjia.android.model.BaseResult;
import cn.shyouchi.wuguanjia.android.subscribers.ProgressSubscriber;
import cn.shyouchi.wuguanjia.android.utils.DisplayUtil;
import cn.shyouchi.wuguanjia.android.widget.GlideCircleTransform;
import cn.shyouchi.wuguanjia.android.widget.TopBar;
import mabeijianxi.camera.MediaRecorderActivity;
import mabeijianxi.camera.VCamera;
import mabeijianxi.camera.model.MediaRecorderConfig;
import mabeijianxi.camera.util.DeviceUtils;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

public class WorkShowMainActivity extends BaseActivity {

    @BindView(R.id.topBar)
    TopBar mTopBar;
    @BindView(R.id.rv_shows)
    RecyclerView mRvShows;

    List<WorkShowEntity> mWorkShowEntities = new ArrayList<>();

    WorkShowAdapter mWorkShowAdapter;


    MenuItem mSendMenuItem;

    ShowApi mShowApi;
    WorkShowEntity firstShow;

    @BindView(R.id.refresh_layout)
    SwipeRefreshLayout mSwipeRefreshLayout;


    View head;


    @Override
    public int initContentView() {


        return R.layout.activity_work_show_main;
    }

    @Override
    public void initInjector() {
        mShowApi = new ShowApi(mContext);

    }

    @Override
    public void initUiAndListener() {

        ButterKnife.bind(this);
        mTopBar.setTitle(getTitle().toString());
        mTopBar.setLeftIcon(R.mipmap.ic_back);
        setSupportActionBar(mTopBar.getToolbar());

        EventBus.getDefault().register(this);

        mWorkShowAdapter = new WorkShowAdapter(mWorkShowEntities, this);
        mRvShows.setAdapter(mWorkShowAdapter);
        mRvShows.setLayoutManager(new LinearLayoutManager(mContext));


        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                fetchShows();
            }
        });


        head = LayoutInflater.from(mContext).inflate(R.layout.view_work_show_header, null);
        ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DisplayUtil.dip2px(mContext, 200));
        head.setLayoutParams(lp);

        View emptyView = LayoutInflater.from(mContext).inflate(R.layout.view_list_empty_layout, null);

        mWorkShowAdapter.setEmptyView(emptyView);

        mWorkShowAdapter.addHeaderView(head);

        fetchShows();

//        initSmallVideo(this);
    }

    @Override
    protected boolean isApplyStatusBarTranslucency() {
        return false;
    }

    @Override
    protected boolean isApplyStatusBarColor() {
        return true;
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        mSendMenuItem = menu.add("发布工作秀");
        mSendMenuItem.setShowAsActionFlags(MenuItem.SHOW_AS_ACTION_ALWAYS);
        mSendMenuItem.setIcon(R.mipmap.ic_work_show_menu_send);
        return super.onCreateOptionsMenu(menu);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (item == mSendMenuItem) {

            startActivity(new Intent(mContext, SendPicWorkShowActivity.class));
//            showSelActionDialog();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    private synchronized void showSelActionDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext, AlertDialog.THEME_HOLO_LIGHT);
        TextView tvTitle = (TextView) getLayoutInflater().inflate(R.layout.dialog_title, null);
        tvTitle.setText("发布工作秀");
        builder.setCustomTitle(tvTitle);
        builder.setItems(new String[]{"相册", "小视频"}, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                switch (which) {
                    case 0:
                        startActivity(new Intent(mContext, SendPicWorkShowActivity.class));
                        break;
                    case 1:
                        go();
                        break;
                }
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("取消", null);
        builder.create().show();
    }


    private void fetchShows() {
        mShowApi.fetchShows()
                .subscribeOn(Schedulers.io())
                .map(new Func1<BaseResult<List<WorkShowEntity>>, List<WorkShowEntity>>() {
                    @Override
                    public List<WorkShowEntity> call(BaseResult<List<WorkShowEntity>> requestResult) {

                        WorkShowEntity selfShow = null;
                        List<WorkShowEntity> showEntities = requestResult.getResultMessage();

                        for (WorkShowEntity workShowEntity : showEntities) {
                            if (workShowEntity.getRank() == 1) {
                                firstShow = workShowEntity;
                            }

                            if (workShowEntity.getMyself() == 1) {
                                selfShow = workShowEntity;
                            }
                        }
                        if (selfShow != null) {
                            showEntities.remove(selfShow);
                            showEntities.add(0, selfShow);
                        }
                        return requestResult.getResultMessage();
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressSubscriber<List<WorkShowEntity>>(mContext) {

                    @Override
                    public void onStart() {
                        super.onStart();
                        firstShow = null;
                    }

                    @Override
                    public void onNext(List<WorkShowEntity> result) {
                        mSwipeRefreshLayout.setRefreshing(false);
                        mWorkShowEntities.clear();
                        mWorkShowEntities.addAll(result);
                        mWorkShowAdapter.notifyDataSetChanged();
                        fillFirstShowDetail();
                    }


                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        mSwipeRefreshLayout.setRefreshing(false);
                    }
                });
    }


    private void fillFirstShowDetail() {
        if (firstShow != null) {
            ImageView imageView = (ImageView) head.findViewById(R.id.img_show);
            ImageView publisher = (ImageView) head.findViewById(R.id.img_publisher);
            TextView project = (TextView) head.findViewById(R.id.tv_project_name);
            loadHead(Global.BASE_URL + firstShow.getId_card_head_image(), publisher);


            project.setText(firstShow.getProjectname());

            if (firstShow.getType() == 1 && !firstShow.getExtra().isEmpty()) {
                String img = "";
                try {
                    for (String s : firstShow.getExtra()) {
                        JSONObject imgJson = new JSONObject(s);
                        if (imgJson.has("image")) {
                            img = Global.BASE_URL + imgJson.getString("image");
                            break;
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }




                loadImg(img, imageView);
            }
        }
    }

    private void loadImg(String path, ImageView imageView) {
        Glide.with(mContext)
                .load(path)
                .into(imageView);
    }

    private void loadHead(String path, ImageView imageView) {
        Glide.with(mContext)
                .load(path)
                .transform(new GlideCircleTransform(mContext))
                .into(imageView);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onLikeChange(LikeChange likeChange) {
        fetchShows();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }


    public void go() {
        MediaRecorderConfig config = new MediaRecorderConfig.Buidler()
                .doH264Compress(true)
                .smallVideoWidth(480)
                .smallVideoHeight(640)
                .recordTimeMax(10 * 1000)
                .maxFrameRate(20)
                .minFrameRate(8)
                .captureThumbnailsTime(1)
                .recordTimeMin((int) (1.5 * 1000))
                .build();
        MediaRecorderActivity.goSmallVideoRecorder(this, SendVideoWorkShowActivity.class.getName(), config);
    }

    public static void initSmallVideo(Context context) {
        // 设置拍摄视频缓存路径
        File dcim = Environment
                .getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        if (DeviceUtils.isZte()) {
            if (dcim.exists()) {
                VCamera.setVideoCachePath(dcim + "/mabeijianxi/");
            } else {
                VCamera.setVideoCachePath(dcim.getPath().replace("/sdcard/",
                        "/sdcard-ext/")
                        + "/mabeijianxi/");
            }
        } else {
            VCamera.setVideoCachePath(dcim + "/mabeijianxi/");
        }
        // 开启log输出,ffmpeg输出到logcat
        VCamera.setDebugMode(false);
        // 初始化拍摄SDK，必须
        VCamera.initialize(context);
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDataChange(DataChangeEvent event) {
        fetchShows();
    }
}
